<?php
/**
 * $Id: tail.php 161 2009-01-31 16:27:24Z surfchen $
 * $URL: http://nehcfrus.googlecode.com/svn/trunk/php/tail.php $
 * @desc    Display the last n lines of a file (20 lines by default).
 * @license http://www.gnu.org/licenses/lgpl.txt LGPL
 * @env     PHP versions 4 and 5
 * @author  surfchen@gmail.com
 * @site    http://www.surfchen.org
 */

/**
 * @param string  $file           the file to be tailled
 * @param int     $lines          how many lines to be tailed
 * @param int     $chunk_size     size to be readed each time 
 * @param string  $ln             tail delimiter 
 *
 * @return string
 */
function tail($file,$lines=20,$chunk_size=2048,$ln="\n") {
    $start=filesize($file);
    $fp=fopen($file,'rb');
    $found=0;
    $result='';
    while ($start>0) {
        if ($start>$chunk_size) {
            $read=$chunk_size;
            $start-=$chunk_size;
        } else {
            $read=$start;
            $start=0;
        }
        fseek($fp,$start,SEEK_SET);
        $bytes=fread($fp,$read);
        $found+=substr_count($bytes,$ln);
        if ($found>$lines) {
            while ($found>$lines) {
                $bytes=substr($bytes,strpos($bytes,$ln)+1);
                $found--;
            }
            $result=$bytes.$result;
            break;
        }
        $result=$bytes.$result;
    }
    fclose($fp);
    return $result;
}
